import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/helper/preferences_helper.dart';
import 'package:wch/native/net_business.dart';
import 'package:wch/page/user_manager.dart';
import 'package:wch/utils/navigator_utils.dart';

import '../constant/event_bus_global.dart';
import '../constant/resource_constant.dart';
import '../model/patient_edit.dart';
import '../model/patient_edit_custom.dart';
import '../utils/log_utils.dart';
import '../utils/toast_utils.dart';
import '../widget/alert_view.dart';
import '../widget/common_widget.dart';
import '../widget/padding_widget.dart';
import '../widget/text_widget.dart';

class UserInfoPage extends StatefulWidget {
  const UserInfoPage(
      {super.key,
      required this.id, required this.isPopKeyBoard});

  final String id;

  final bool isPopKeyBoard;

  @override
  State<UserInfoPage> createState() => _UserInfoPageState();
}

class _UserInfoPageState extends State<UserInfoPage>{
  PatientEditModel detailEntity = PatientEditModel();

  final PatientCustomModel patientEditModel = PatientCustomModel();

  List<Widget> allWidget = [];

  OverlayEntry? entry;

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xFFF8F9FB),
      child: Stack(
        children: [
          Container(),
          Positioned(
            left: 0,
            right: 0,
            top: 0,
            bottom: widget.isPopKeyBoard ? 0 : 115.h,
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [],
                  ),
                  Container(
                      margin: EdgeInsets.symmetric(horizontal: 15.w),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(7.5.h)),
                      ),
                      child: Column(
                        children: allWidget,
                      )
                  ),

                ],
              ),
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            height: widget.isPopKeyBoard ? 0 : 115.h,
            child: Column(
            children: [
              Visibility(
                visible:!widget.isPopKeyBoard,
                child: VerPadding(30.h),),
              Visibility(
                visible:!widget.isPopKeyBoard,
                child: Container(
                  child: CommonBtn(
                    title: '保存',
                    callback: () {
                      _savedLogic();
                    },
                  ),
                  margin: EdgeInsets.symmetric(horizontal: 40.w),
                ),),
              Visibility(
                visible:!widget.isPopKeyBoard,
                child: VerPadding(40.h),),
            ],
          ))
        ],

      ),
    );
  }

  @override
  void initState() {
    super.initState();

    NetBusiness().patientDetail(widget.id).then((value) {
      detailEntity = value;
      patientEditModel.templateId = value.templateId!.toString();
      patientEditModel.id = value.id!.toString();
      _getDetailWidget();
    });
  }

  void _refreshId(int id) {
    PatientEditList model = detailEntity.list![id];
    if (model.type! == 0 || model.type! == 1) {
      if (model.name == '科室') {
        allWidget[id] = _getDepartmentWidget(
            model.controller!, model, id != detailEntity.list!.length - 1);
      } else {
        allWidget[id] = _getInputWidget(
            model.controller!, model, id != detailEntity.list!.length - 1);
      }
    } else if (model.type! == 3) {
      allWidget[id] =
          _getSelectWidget(id, model, id != detailEntity.list!.length - 1);
    } else {
      allWidget[id] =
          _getSelectWidget(id, model, id != detailEntity.list!.length - 1);
    }
    setState(() {
      allWidget;
    });
  }

  void _savedLogic() {
    ///先校验是否为空
    for (int i = 0; i < patientEditModel.list.length; i++) {
      Map<String, String> map = patientEditModel.list[i];
      if (map['status'] == 'Y') {
        if (map['text'] == '') {
          ToastUtils.showToast(msg: '${map['name']}不能为空');
          return;
        }
      }
    }
    NetBusiness()
        .editPatient(patientEditModel.id, patientEditModel.templateId,
        patientEditModel.list)
        .then((value) {
      if (value) {
        ToastUtils.showToast(msg: '修改成功');
        globalEventBus.fire(EventBufRefreshModel());
        NavigatorUtil.pop(context);
      }
    });
  }

  void _getDetailWidget() {
    patientEditModel.list.clear();
    for (int i = 0; i < detailEntity.list!.length; i++) {
      PatientEditList model = detailEntity.list![i];
      TextEditingController controller = TextEditingController();
      model.controller = controller;
      controller.addListener(() {
        Map<String, String> map = patientEditModel.list[i];
        map['text'] = controller.text;
      });

      patientEditModel.list.add({
        'templateItemId': model.templateItemId.toString(),
        'text': model.text ?? '',
        'status': model.status ?? '',
        'name': model.name ?? ''
      });

      if (model.type! == 0 || model.type! == 1) {
        if (model.name == '科室') {
          allWidget.add(_getDepartmentWidget(
              controller, model, i != detailEntity.list!.length - 1));
        } else {
          allWidget.add(_getInputWidget(
              controller, model, i != detailEntity.list!.length - 1));
        }

        // widgetHeight += 52.h;
      } else if (model.type! == 3) {
        allWidget.add(_getMulLineWidget(
            controller,
            model.name!,
            model.text,
            '请选择${model.name}',
            model.type!,
            i != detailEntity.list!.length - 1));
        // widgetHeight += 104.h;
      } else {
        allWidget.add(
            _getSelectWidget(i, model, i != detailEntity.list!.length - 1));
        // widgetHeight += 52.h;
      }
    }

    setState(() {
      allWidget;
    });
  }

  Widget _getInputWidget(TextEditingController controller,
      PatientEditList model, bool isNeedLine) {
    controller.text = model.text ?? '';
    return Container(
      height: 52.h,
      child: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                HorPadding(20.w),
                Container(
                  width: 120.w,
                  child: F15TitleText(model.name!, color: F1TextColor),
                ),
                Expanded(
                    child: CupertinoTextField(
                  placeholderStyle: TextStyle(
                    color: hintColor,
                    fontSize: 15.w,
                  ),
                  placeholder: '请输入${model.name}',
                  controller: controller,
                  style: TextStyle(color: F1TextColor, fontSize: 15.w),
                  decoration: const BoxDecoration(color: Colors.transparent),
                  keyboardType: model.type == 0
                      ? TextInputType.number
                      : TextInputType.text,
                )),
                HorPadding(20.w)
              ],
            ),
          ),
          Offstage(
            offstage: !isNeedLine,
            child:
                LineWidget(width: ScreenUtil().screenWidth - 30.w, height: 0.5),
          )
        ],
      ),
    );
  }

  Widget _getDepartmentWidget(TextEditingController controller,
      PatientEditList model, bool isNeedLine) {
    return Container(
      height: 52.h,
      child: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                HorPadding(20.w),
                Container(
                  width: 120.w,
                  child: F15TitleText(model.name!, color: F1TextColor),
                ),
                Expanded(
                    child: Row(
                      children: [
                        HorPadding(5.5.w),
                        F15TitleText(PreferencesHelper.getDepartment()!, color: F1TextColor),
                      ],
                    ),),
                HorPadding(20.w)
              ],
            ),
          ),
          Offstage(
            offstage: !isNeedLine,
            child:
                LineWidget(width: ScreenUtil().screenWidth - 30.w, height: 0.5),
          )
        ],
      ),
    );
  }

  Widget _getMulLineWidget(TextEditingController controller, String label,
      String? content, String? hint, int inputType, bool isNeedLine) {
    controller.text = content ?? '';
    return Container(
      height: 104.h,
      child: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                HorPadding(20.w),
                Container(
                  width: 120.w,
                  child: F15TitleText(label, color: F1TextColor),
                ),
                Expanded(
                    child: Container(
                  height: 84.h,
                  padding: EdgeInsets.symmetric(vertical: 10.h),
                  child: CupertinoTextField(
                    placeholderStyle: TextStyle(
                      color: hintColor,
                      fontSize: 15.w,
                    ),
                    maxLines: 10,
                    maxLength: 50,
                    controller: controller,
                    // style: TextStyle(color: F1TextColor, fontSize: 15.w),
                    // decoration: BoxDecoration(color: Colors.transparent),
                    keyboardType: inputType == 0
                        ? TextInputType.number
                        : TextInputType.text,
                  ),
                )),
                HorPadding(20.w)
              ],
            ),
          ),
          Offstage(
            offstage: !isNeedLine,
            child:
                LineWidget(width: ScreenUtil().screenWidth - 30.w, height: 0.5),
          )
        ],
      ),
    );
  }

  Widget _getSelectWidget(int id, PatientEditList data, bool isNeedLine) {
    // if (widget.isPopKeyBoard) {
    //   return _getSubSelectWidget(id, data, isNeedLine);
    // } else {
    return InkWell(
        onTap: () {
          if (widget.isPopKeyBoard) {
            return;
          }

          if (data.type == 2) {
            entry = OverlayEntry(builder: (ctx) {
              return SelectDatePicker(
                  callback: (date, age) {
                    data.text = date;
                    Map map = patientEditModel.list[id];
                    map['text'] = date;
                    _refreshId(id);
                  },
                  overlay: entry!,
                  date: data.text!,
                  title: '请选择日期');
            });
            Overlay.of(context).insert(entry!);
          } else if (data.type == 4 || data.type == 5 || data.type == 6) {
            if (data.name == '性别'){
              data.label = '男,女';
            }
            entry = OverlayEntry(builder: (ctx) {
              // return SelectSexPicker(callback: (sex){
              //   data.text = sex;
              //   _refreshId(id);
              // }, overlay: entry!);
              return SelectSinglePicker(
                callback: (item) {
                  LogUtils.log('log=$item');
                  data.text = item;
                  Map map = patientEditModel.list[id];
                  map['text'] = item;
                  _refreshId(id);
                },
                overlay: entry!,
                items: data.label!.split(','),
                title: '请选择${data.name}',
              );
            });
            Overlay.of(context).insert(entry!);
          }
        },
        child: _getSubSelectWidget(id, data, isNeedLine));
    // }
  }

  Widget _getSubSelectWidget(int id, PatientEditList data, bool isNeedLine) {
    return Container(
      height: 52.h,
      child: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                HorPadding(20.w),
                Container(
                  width: 127.w,
                  child: F15TitleText(data.name!, color: F1TextColor),
                ),
                Expanded(
                    child: F15TitleText(
                  data.text ?? '请选择${data.name}',
                  color: data.text != null ? F1TextColor : hintColor,
                )),
                HorPadding(10.w),
                Image.asset(
                  arrowRightPng,
                  width: 11.w,
                  height: 11.w,
                ),
                HorPadding(20.w)
              ],
            ),
          ),
          Offstage(
            offstage: !isNeedLine,
            child:
                LineWidget(width: ScreenUtil().screenWidth - 30.w, height: 0.5),
          )
        ],
      ),
    );
  }
}
